package com.iter.devbox.servlet3;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet3 示例
 * 
 * @author jinxin
 */
@WebServlet(urlPatterns={"/myServlet3"}, asyncSupported=true, name="myServlet3", loadOnStartup=1, 
initParams={@WebInitParam(name="username", value="hnylj", description="this is initParam")}, description="Servlet3", displayName="The Servlet 3.0")
public class MyServlet3 extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
    public MyServlet3() {
        super();
    }

	public void init(ServletConfig config) throws ServletException {
		System.out.println(config.getServletName());
		System.out.println(config.getInitParameter("username"));
	}

	public void destroy() {
	}

	public ServletConfig getServletConfig() {
		System.out.println(super.getServletConfig().getServletContext());
		return super.getServletConfig();
	}

	public String getServletInfo() {
		return null; 
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("进入Servlet时间：" + System.currentTimeMillis());
        out.flush();

        //在子线程中执行业务调用，并由其负责输出响应，主线程退出
        AsyncContext ctx = request.startAsync();
        //异步执行监听器
        ctx.addListener(new AsyncListener() {
        	/**异步执行完成时调用*/
			@Override
			public void onComplete(AsyncEvent event) throws IOException {
				System.out.println("异步执行完成，可以做一些清理工作......");
			}
			/**异步线程执行超时*/
			@Override
			public void onTimeout(AsyncEvent event) throws IOException {
				System.out.println("异步执行超时......");
			}
			/**异步线程出错时调用*/
			@Override
			public void onError(AsyncEvent event) throws IOException {
				System.out.println("异步执行出错......");
			}
			/**异步线程开始时*/
			@Override
			public void onStartAsync(AsyncEvent event) throws IOException {
				System.out.println("异步执行开始......");
			}
        });
        
        ctx.start(new BizRunnable(ctx));
        //开启线程执行
        //new Thread(new BizRunnable(ctx)).start();

        out.println("结束Servlet的时间：" + System.currentTimeMillis());
        out.flush();
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter pw = response.getWriter();
		pw.println("doPost......");
		pw.println("Hello World!");
	}
}

/**
 * 异步业务处理线程
 * 
 * @author jinxin
 */
class BizRunnable implements Runnable {
	
	private AsyncContext ctx = null;
	
    public BizRunnable (AsyncContext ctx){
        this.ctx = ctx;
    }

	@Override
	public void run() {
		try {
            //等待十秒钟，以模拟业务方法的执行
            Thread.sleep(6000);
            PrintWriter out = ctx.getResponse().getWriter();
            out.println("业务处理完毕的时间：" + System.currentTimeMillis());
            out.flush();
            ctx.complete();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}
